<?php
	class DataBaseConnect
	{
		const QUERY_TYPE_SELECT = 'SELECT';
		const QUERY_TYPE_INSERT = 'INSERT';
		
		private $con = 1;
		
		public function __construct()
		{
			$this->con = NULL;
		}
		public function connect( $host, $userName, $pass, $databaseName )
		{
			if( $this->con == NULL )
			{
				$this->con = mysqli_connect( $host, $userName, $pass, $databaseName  );
				if( mysqli_connect_errno() )
				{
					throw new Exception( 'Failed to connect to MySQL: ' . mysqli_connect_error() );
					return;
				}
			}
		}
		
		public function close()
		{
			if( $this->con != NULL )
			{
				mysqli_close( $this->con );
				$this->con = NULL;
			}
		}
		
		public function query( $query )
		{
			if( $this->con == NULL )
			{
				throw new Exception( 'Not Aready Connection :: QUERY = '.$query );
				return 0;
			}
			return mysqli_query( $this->con, $query );
		}
		
		// 
		public static function fetch_array( $result )
		{
			return mysqli_fetch_array( $result );
		}
		
		//
		public static function fetch_assoc( $result )
		{
			return mysqli_fetch_assoc( $result );
		}
		
		//
		public static function num_rows( $result )
		{
			return mysqli_num_rows( $result );
		}
		
		// INSERT 되고 난 직후의 PK ID
		public function insert_id()
		{
			return mysqli_insert_id( $this->con );
		}
		
		public function affected_rows()
		{
			return mysqli_affected_rows( $this->con );
		}
			
		
		// 디버깅용 출력
		public static function trace( $result, $queryType )
		{
			$log = '[DataBaseConnect::trace start] ';
			
			if( $queryType == self::QUERY_TYPE_SELECT )
			{
				$log = $log.'SELECT<br/>';
				while( $row = mysqli_fetch_assoc($result) )
				{
					$log = $log.'---------<br/>';
					foreach( $row as $key=>$value )
					{
						$log = $log.'['.$key.'] => '.$value.'<br/>';
					}
				}
			}else if( $queryType == self::QUERY_TYPE_INSERT )
			{
				$log = $log.'INSERT<br/>';
				$log = $log.$result.'<br/>';
			}else{
				$log = $log.'ETC<br/>';
				$log = $log.$result.'<br/>';
			}
			
			$log = $log.'[DataBaseConnect::trace end]';
			return $log;
		}
		
		// fetch 오브젝트의 key / value 를 XML Node 형태로 열거한다.
		public static function fetchSerialize( $fetch, $keys )
		{
			$response = array();
			if( $keys )
			{
				foreach( $keys as $key )
				{
					$response[ strtolower( $key ) ] = $fetch[ $key ];
				}
			}else{
				foreach( $fetch as $key=>$value )
				{
					if( !is_numeric( $key ) )	// 숫자형 인덱스는 제외시킨다.
						$response[ strtolower( $key ) ] = $value;
				}
			}
			return $response;
		}
	}
?>